package medicalDocumentation.medicalRepository;

import entity.MedicalProcedure;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class MedicalProcedureRepositorySessionBean implements MedicalProcedureRepositorySessionBeanRemote {

    public final String MEDICAL_PROCEDURE_CODE_REQUIRED = "Medical procedure code required";
    public final String DUPLICATE_MEDICAL_PROCEDURE_CODE = "Duplicate medical procedure code";
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public String addMedicalProcedure(String code, String name,String procedure, String remark,String price) {
        if (code == null) {
            return MEDICAL_PROCEDURE_CODE_REQUIRED;
        }
        if (getMedicalProcedureByCode(code).size() > 0) {
            return DUPLICATE_MEDICAL_PROCEDURE_CODE;
        }
        MedicalProcedure medicalProcedure = new MedicalProcedure();
        medicalProcedure.setCode(code);
        medicalProcedure.setName(name);
        medicalProcedure.setProcedure(procedure);
        medicalProcedure.setRemark(remark);
        medicalProcedure.setPrice(price);
        entityManager.persist(medicalProcedure);
        entityManager.flush();
        return medicalProcedure.getCode();
    }

    @Override
    public List<MedicalProcedure> getMedicalProcedureByCode(String code) {
        String strQuery = "SELECT d FROM MedicalProcedure d WHERE d.code = :inCode";
        Query query = entityManager.createQuery(strQuery);
        query.setParameter("inCode", code);
        return query.getResultList();
    }

    @Override
    public List<MedicalProcedure> getAllMedicalProcedure() {
        String strQuery = "SELECT m FROM MedicalProcedure m";
        Query query = entityManager.createQuery(strQuery);
        return query.getResultList();
    }

    @Override
    public void deleteMedicalProcedure(String code) {
        List medicalProcedures = getMedicalProcedureByCode(code);
        if (medicalProcedures.get(0) != null) {
            entityManager.remove(medicalProcedures.get(0));
            entityManager.flush();
        }
    }

    @Override
    public void updateMedicalProcedure(String code, String name, String procedure, String remark,String price) {
        MedicalProcedure medicalProcedure = getMedicalProcedureByCode(code).get(0);
        if (medicalProcedure != null) {
            medicalProcedure.setName(name);
            medicalProcedure.setProcedure(procedure);
            medicalProcedure.setRemark(remark);
            medicalProcedure.setPrice(price);
            entityManager.merge(medicalProcedure);
            entityManager.flush();
        }
    }
}
